package by.dkusch.aircompany.webapp.page.base.validator;

import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

import by.dkusch.aircompany.model.tables.base.BaseEntity;
import by.dkusch.aircompany.services.AbstractService;

public class UniqueFieldValidator<ID, Entity extends BaseEntity<ID>> implements IValidator<String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Entity entity;
	private AbstractService<ID, Entity> service;
	private SingularAttribute<? super Entity, String> attr;

	public UniqueFieldValidator(SingularAttribute<? super Entity, String> attr, AbstractService<ID, Entity> service, Entity entity) {
		this.attr = attr;
		this.entity = entity;
		this.service = service;
	}

	@Override
	public void validate(IValidatable<String> validatable) {
		final String field = validatable.getValue();
		if (!service.checkUniqueByFieldRestrictionAnyCase(attr, field, entity == null ? null : entity.getId())) {
			error(validatable, "error.field.notunique");
		}
	}

	protected void error(IValidatable<String> validatable, String errorKey) {
		ValidationError error = new ValidationError();
		error.addKey(getClass().getSimpleName() + "." + errorKey);
		validatable.error(error);
	}

	public Entity getEntity() {
		return entity;
	}

	public AbstractService<ID, Entity> getService() {
		return service;
	}

	public SingularAttribute<? super Entity, String> getAttr() {
		return attr;
	}

}
